<template>
  <div class="type" v-loading="loading" element-loading-text="加载中...">
    <div class="header flex-justify-between">
      <div style="display: flex; gap: 5px">
        <HPlainButton @click="addType"> 添加技能</HPlainButton>
        <el-dropdown trigger="click">
          <HButton :disabled="selecttion.length == 0">
            批量操作
            <el-icon class="el-icon--right">
              <ArrowDown />
            </el-icon>
          </HButton>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="changeAll(1)">
                <el-icon>
                  <CircleCheck />
                </el-icon>
                批量启用
              </el-dropdown-item>
              <el-dropdown-item @click="changeAll(2)">
                <el-icon>
                  <Warning />
                </el-icon>
                批量禁用
              </el-dropdown-item>
              <el-dropdown-item @click="changeAll(3)">
                <el-icon>
                  <Delete />
                </el-icon>
                批量删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <div class="search flex-align-center">
        <el-input
          v-model="name"
          placeholder="技能名称"
          class="input-width"
          clearable
          @keyup.enter="getList"
           @clear="getList"
        />
        <HButton type="primary" @click="getList">
          <el-icon>
            <Search />
          </el-icon>
          搜索
        </HButton>
      </div>
    </div>
    <div class="table-grade">
      <el-table
        border
        stripe
        resizable
        @selection-change="handleChange"
        ref="tableDom"
        :data="tableData"
        height="100%"
        style="position: absolute"
      >
        <el-table-column type="selection" width="40" fixed />
        <el-table-column show-overflow-tooltip type="index" label="序号" width="50" />
        <el-table-column show-overflow-tooltip prop="name" label="技能名称" min-width="150" />
        <el-table-column show-overflow-tooltip prop="name" label="状态" width="70">
          <template #default="scope">
            <HStatus v-if="scope.row.status" type="info">禁用</HStatus>
            <HStatus v-else>启用</HStatus>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="createTime" label="创建时间" width="170" />
        <el-table-column show-overflow-tooltip prop="updateTime" label="更新时间" width="170" />
        <el-table-column fixed="right" label="操作" width="60">
          <template #default="scope">
            <HLink @click="editType(scope.row.id)">详细</HLink>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="footer flex-justify-end">
      <Pagination
        ref="pagination"
        :list_total="total"
        @size-change="getList"
        @current-change="getList"
      />
    </div>

    <!-- 添加/编辑  技能名称弹窗 -->
    <HModal v-model="addDialog" size="small">
      <template #header>
        <div class="my-header">
          <h3 class="title">{{ formTitle }}</h3>
        </div>
      </template>
      <div v-loading="formLoading">
        <div class="form-text">
          <el-form
            label-width="70"
            ref="formRef"
            :rules="rules"
            :model="form"
            @validate="handleFormValidate"
          >
            <!-- 技能名称 -->
            <el-form-item label="技能名称" :style="getFormItemStyle['name']" prop="name">
              <el-input v-model="form.name" clearable placeholder="请输入名称" />
            </el-form-item>

            <!-- 技能状态 -->
            <el-form-item label="技能状态" class="form_radio_item">
              <el-radio-group v-model="form.status">
                <el-radio :value="false">
                  <span class="bg_text">启用</span>
                </el-radio>
                <el-radio :value="true">
                  <span class="bg_text">禁用</span>
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <template #footerLeft>
        <HPlainBgButton
          is-modal
          type="error"
          @focus="(e: Event) => (e.target as HTMLButtonElement).blur()"
          @click="changeAll(33)"
          v-show="formTitle == '编辑技能'"
          >删除</HPlainBgButton
        >
      </template>

      <template #footerRight>
        <HButton is-modal type="primary" @click="saveData(formRef)">保存</HButton>
        <HButton is-modal @click="onClose">取消</HButton>
      </template>
    </HModal>
  </div>
</template>

<script setup lang="ts">
  import Pagination from '@/components/Pagination/index.vue'
  import { ref, reactive, markRaw } from 'vue'
  import type { FormInstance } from 'element-plus'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Search, Delete, Warning, ArrowDown, CircleCheck } from '@element-plus/icons-vue'
  import {
    getNetworkSkillList,
    getNetworkSkillDelete,
    getNetworkSkillDisable,
    getNetworkSkillDetail,
    getNetworkfieldcSkillSave,
  } from '@/api/network'
  import { EngineerSkill } from './types'
  import HPlainButton from '@/components/common/button/HPlainButton.vue'
  import HButton from '@/components/common/button/HButton.vue'
  import HStatus from '@/components/common/status/HStatus.vue'
  import HLink from '@/components/common/link/HLink.vue'
  import HPlainBgButton from '@/components/common/button/HPlainBgButton.vue'
  import HModal from '@/components/common/Modal/HModal.vue'
  import useFormValidateService from '@/service/common/useFormValidate/useFormValidateService'

  /**
   * 使用表单验证服务
   */
  const { handleFormValidate, resetFormValidateResult, getFormItemStyle } = useFormValidateService([
    { name: 'name', isSelect: false, errMarginBottom: 24 },
  ])

  /**
   * 弹窗关闭事件
   */
  const onClose = () => {
    addDialog.value = false
    resetFormValidateResult()
  }

  const name = ref('') // 技能名称

  const tableData = ref<Array<EngineerSkill>>([]) // 列表数据
  const tableDom = ref() // 列表dom

  const pagination = ref() // 分页dom
  const total = ref() // 总数目

  const addDialog = ref(false)
  const loading = ref(false)

  const formTitle = ref('')
  const formLoading = ref(false)

  const form = reactive({
    id: null,
    name: '',
    status: false,
  })

  // 表单元素
  const formRef = ref<FormInstance>()

  // 验证规则
  const rules = reactive({
    name: [{ required: true, message: '请输入技能名称', trigger: ['blur', 'change'] }],
  })

  // 获取表格选中的数据
  const selecttion = ref([])
  const handleChange = (val: Array<EngineerSkill>) => {
    if (val.length != 0) {
      val.forEach((item) => {
        if (Object.values(selecttion.value).indexOf(item.id) == -1) {
          selecttion.value.push(item.id)
        } else {
          selecttion.value = selecttion.value.filter((i) => i == item.id)
        }
      })
    } else {
      selecttion.value = []
    }
  }

  // 获取分页数据
  const getPageData = () => {
    return {
      limit: pagination.value.size,
      name: name.value,
      page: pagination.value.current,
    }
  }

  // 获取列表数据
  const getList = async () => {
    loading.value = true
    const res = await getNetworkSkillList(getPageData())
    tableData.value = res.data.data.rows
    total.value = parseInt(res.data.data.total)
    loading.value = false
  }

  // 添加技能
  const addType = () => {
    formTitle.value = '添加技能'
    form.id = null
    form.name = ''
    form.status = false
    addDialog.value = true
  }

  // 编辑技能
  const editType = async (id) => {
    addDialog.value = true
    formTitle.value = '编辑技能'
    formLoading.value = true
    await getNetworkSkillDetail(id).then((res) => {
      form.id = res.data.data.row.id
      form.name = res.data.data.row.name
      form.status = res.data.data.row.status
    })
    formLoading.value = false
  }

  // 保存方法
  const saveMethod = (method, data, dialog, load) => {
    load.value = true
    method(data).then((res) => {
      if (res.data.success == true) {
        ElMessage({
          message: res.data.message,
          type: 'success',
          duration: 2000,
        })
        dialog.value = false
        load.value = false
        getList()
      } else {
        if (res.data.isError)
          ElMessage({
            message: res.data.message,
            type: 'warning',
            duration: 2000,
          })
        load.value = false
        return
      }
    })
  }

  // 保存技能
  const saveData = (formEl: FormInstance | undefined) => {
    formEl.validate((valid) => {
      if (valid) {
        saveMethod(getNetworkfieldcSkillSave, form, addDialog, formLoading)
      }
    })
  }

  // 批量操作的方法
  const changeMethod = (type, method, arr, status, dialog) => {
    if (arr.length == 0) {
      ElMessage({
        message: `请选择要${type}的技能`,
        type: 'warning',
        duration: 2000,
      })
      return
    }
    ElMessageBox({
      type: type == '删除' ? 'error' : 'warning',
      title: '提示',
      icon: type == '删除' ? markRaw(Delete) : markRaw(Warning),
      message: `确认${type}选中的技能?`,
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      autofocus: false,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '加载中...'
          setTimeout(() => {
            done()
            setTimeout(() => {
              instance.confirmButtonLoading = false
            }, 0)
          }, 1000)
        } else {
          done()
        }
      },
    }).then(async () => {
      if (status != 3) {
        const res = await method(arr, status)
        ElMessage({
          message: res.data.message,
          type: 'success',
          duration: 2000,
        })
      } else {
        const res = await method(arr)
        ElMessage({
          message: res.data.message,
          type: 'success',
          duration: 2000,
        })
        if (dialog != '') {
          dialog.value = false
        }
      }
      tableDom.value.clearSelection()
      getList()
    })
  }

  // 修改技能状态
  const changeAll = (param: 1 | 2 | 3 | 33) => {
    if (param === 1) {
      changeMethod('启用', getNetworkSkillDisable, selecttion.value, false, '')
    }
    if (param === 2) {
      changeMethod('禁用', getNetworkSkillDisable, selecttion.value, true, '')
    }
    if (param === 3) {
      changeMethod('删除', getNetworkSkillDelete, selecttion.value, 3, '')
    }
    if (param === 33) {
      changeMethod('删除', getNetworkSkillDelete, [form.id], 3, addDialog)
    }
  }

  // 返回方法
  defineExpose({ getList })
</script>

<style scoped lang="scss">
  @import '../../index.scss';
</style>
